#include "App.h"
#include "remoteServer/Client.h"
#include "Recordable.h"
#include "monitor/Monitor.h"
#include <iostream>
#include "Windows.h"

App::App()
{
	this->m_server = new Client(nullptr, 9001, 30);
	this->m_server->setOnMessageCallbackFunction(std::bind(&App::on_message, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5));
	this->m_server->setOnConnectedCallbackFunction(std::bind(&App::on_connected, this, std::placeholders::_1));
	this->m_server->setOnClosedCallbackFunction(std::bind(&App::on_closed, this, std::placeholders::_1));

	
	// this->loadExludeWindow();
	this->get_all_window();
}

Recordable* App::get_recordable_window(int index)
{
	if (this->m_recordable_window_v == nullptr) {
		return nullptr;
	}
	if (index > this->m_recordable_window_v->size()-1 || index < 0) {
		return nullptr;
	}
	return this->m_recordable_window_v->at(index);
}

App::~App()
{
	// clear
	this->clear_recordable_window();
	this->clear_monitor();

	delete this->m_server;

}

void App::start_server()
{
	this->m_server->start();
}

void App::stop_server()
{
	this->m_server->stop();
}

void App::get_all_window()
{
	if (this->m_recordable_window_v != nullptr) {
		this->clear_recordable_window();
	}
	this->m_recordable_window_v = new std::vector<Recordable*>();
	find_all_recordable_window(std::bind(&App::find_all_recordable_window_callback, this, std::placeholders::_1));
}

void App::get_all_monitor()
{
	this->clear_monitor();
	enum_monitor(this->m_monitor_v);
}

void App::clear_recordable_window()
{
	for (auto temp : *this->m_recordable_window_v) {
		release_recordable(temp);
	}
	delete this->m_recordable_window_v;
	this->m_recordable_window_v = nullptr;
}

void App::clear_monitor()
{
	if (this->m_monitor_v != nullptr) {
		release_monitor_v(this->m_monitor_v);
		this->m_monitor_v = nullptr;
	}
}

bool App::on_message(unsigned int _conv, char* _key, char* _payload, char* _res_key, char* _response)
{
	std::cout << _conv << ": " << _payload << std::endl;

	delete _key;
	delete _payload;
	return false;
}

bool App::on_connected(unsigned int conv)
{
	std::cout << conv << " onConnected" << std::endl;
	return false;
}

bool App::on_closed(unsigned int conv)
{
	std::cout << conv << " onClosed" << std::endl;
	return false;
}

void App::find_all_recordable_window_callback(Recordable* _recordable)
{
	if (this->m_recordable_window_v == nullptr) {
		return;
	}
	this->m_recordable_window_v->push_back(_recordable);
}
